import React, {
  memo,
  useCallback,
  useEffect,
  useRef,
  useState,
} from "react";
import { connect } from "react-redux";
import { withSoundCloudAudio } from "react-soundplayer/addons";
import {
  PlayButton,
  Progress,
  VolumeControl,
  PrevButton,
  NextButton,
} from "react-soundplayer/components";

import MinAndMax from "../MinAndMax";
import style from "./index.css";
import PlayerListTop from "./PlayerListTop";
import { setCurrentTime, setCurrentSongDetail } from '@/redux/actions'

const stylePass = {
  position: "fixed",
  bottom: "0",
  width: "100%",
  borderTop: `1px solid #ececec`,
  background: '#2e2e2e'
};

const Player = memo((props) => {
  const { soundCloudAudio, playing, duration, currentTime, songsList, currentSongDetail, setNewSongs, setCurrentTimeAct, setCurrentSongDetailAct, onEnd, brotherNodeChangeTime } = props;

  const playbtnRef = useRef(null)
  const [currentTimeWithmh, setCurrenttimewithmh] = useState(0);
  const [durationWithmh, setDurationwithmh] = useState(0);
  const [isStar, setIsStar] = useState(true);
  const [type, settype] = useState(1);
  const [showPlaylist, setShowplaylist] = useState(false);

  // console.log(soundCloudAudio, "currentSongDetail");


  useEffect(() => {
    // console.log(currentTime, 'currentTime');
    setCurrentTimeAct(currentTime)
    if (duration == 0) {
      setDurationwithmh("0:00");
    } else {
      setDurationwithmh(getTimeWithMh(duration));
    }
    if (currentTime == 0) {
      setCurrenttimewithmh("0:00");
    } else {
      setCurrenttimewithmh(getTimeWithMh(currentTime));
    }

  }, [duration, currentTime]);

  const getRandomInt = (min, max) => {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min)) + min; //不含最大值，含最小值
  }

  useEffect(() => {
    if (type == 1) {
      // 顺序
      lastandnextChick('next')
    }else if(type == 2){
      // 随机
      let len = songsList.length
      console.log(len, 'le')
      let i = getRandomInt(1, len)
      let currentI = songsList.findIndex(e => e.id == currentSongDetail.id)
      if (currentI == i) {
        i = getRandomInt(1, len)
      }
      let sl = songsList
      setCurrentSongDetailAct(sl[i].id)
    }else{
      // 单曲
      return
    }
  }, [onEnd])

  const getTimeWithMh = useCallback(
    (duration) => {
      let minOne = parseInt(duration / 60);
      let secondOne = (duration / 60 - parseInt(minOne)).toFixed(2);
      secondOne = parseInt(secondOne * 60);
      if (secondOne / 10 < 1) {
        secondOne = "0" + secondOne;
      }
      return `${minOne}:${secondOne}`;
    },
    [duration, currentTime]
  );

  const toggleStar = useCallback(() => {
    let isS = !isStar;
    setIsStar(isS);

    console.log("toggleStar");
  }, [isStar]);

  const setThreeStatus = useCallback(() => {
    let t = type + 1;
    if (t > 3) {
      t = 1;
    }
    settype(t);
  }, [type]);

  const lastandnextChick = useCallback((e) => {
    if (!songsList.length) {
      return
    }
    // prev,next
    console.log(e, 'eee')

    let sl = songsList
    let cd = currentSongDetail
    let len = songsList.length
    let i = sl.findIndex(e => cd.id == e.id)
    
    if (e == 'prev') {
      i = (i - 1 < 0) ? (len - 1) : (i - 1)
      console.log(sl[i], 'sl[i] p');
      setCurrentSongDetailAct(sl[i].id)
    } else {
      i = (i + 1 > (len - 1)) ? 0 : (i + 1)
      console.log(sl, i, 'sl i')
      console.log(sl[i], 'sl[i] n');
      setCurrentSongDetailAct(sl[i].id)
    }
    soundCloudAudio.audio.autoplay = true
  }, [songsList, currentSongDetail, soundCloudAudio]);

  const showPlaylistFun = useCallback(() => {
    console.log('showPlaylistFun')
    let isshow = !showPlaylist;
    setShowplaylist(isshow);
  }, [showPlaylist]);

  const togglePauseAndPlay = useCallback(() => {
    if (playing) {
      soundCloudAudio.audio.pause()
    }else{
      soundCloudAudio.audio.play()
    }
    
  }, [playing])

  const playSong = useCallback(async (song) => {
    // await setNewSongs(song)
    let id = song.id
    console.log(id, 'id');
    setNewSongs(id)
    
    soundCloudAudio.audio.autoplay = true
  }, [soundCloudAudio]);

  useEffect(() => {
    console.log(soundCloudAudio, 'soundCloudAudio')
    soundCloudAudio.audio.autoplay = true
  }, [brotherNodeChangeTime])

  return (
    <MinAndMax bgc="#2e2d2d" stylePass={stylePass}>
      <div className={[style.content, style.playerContaniner].join(" ")}>
        <div className={style.btngroup}>
          <img
            src={require("./Icon/last.svg").default}
            alt="svg"
            className={style.iconNormal}
            onClick={() => lastandnextChick('prev')}
          />
          {/* <PrevButton onPrevClick={() => lastandnextChick("last")} {...props} /> */}
          {/* <PlayButton
            className="custom-player-btn"
            onPlayClick={() => {
              console.log("play button clicked!");
            }}
            {...props}
          /> */}
          <img
            src={require(`./Icon/${playing ? 'pause' : 'play'}.svg`).default}
            alt={`${playing ? '暂停' : '播放'}`}
            onClick={togglePauseAndPlay}
            className={[style.iconNormal, style.iconpp].join(" ")}
          />
          <img
            src={require("./Icon/last.svg").default}
            alt="svg"
            className={style.iconNormal}
            onClick={() => lastandnextChick('next')}
            style={{ transform: "rotate(180deg)" }}
          />
          {/* <NextButton onPrevClick={() => lastandnextChick("next")} {...props} /> */}

          <VolumeControl
            className="mr2 flex flex-center"
            buttonClassName="flex-none h2 button button-transparent button-grow rounded"
            rangeClassName="custom-track-bg"
            volume={0.5}
            {...props}
          />
        </div>
        <div className={style.slider}>
          <img
            src={
              currentSongDetail &&
                currentSongDetail.al &&
                currentSongDetail.al.picUrl
                ? currentSongDetail.al.picUrl
                : "http://s4.music.126.net/style/web2/img/default/default_album.jpg"
            }
            alt="musicPic"
            className="musicPic"
          />
          {/* <Slider
            defaultValue={0}
            disabled={false}
            value={currentTime}
            max={100}
            min={0}
            style={{ flex: "1", marginBottom: "0" }}
          /> */}
          <div className={style.sliderProgress}>
            <div className={style.nameinProgress}>
              {currentSongDetail.name ? (
                <div className={style.lineproTop}>
                  <div className={[style.currentsongName, style.textOverflow].join(' ')}>
                    {currentSongDetail.name || '无名'}
                  </div>
                  <div className={[style.currentsongAr, style.textOverflow].join(' ')}>
                    {currentSongDetail.ar.map((aritem, i) => (
                      <div key={aritem.id}>
                        {i > 0 ? "/" : ""} {aritem.name}
                      </div>
                    )) || "未知"}
                  </div>
                  <img
                    src={require("./Icon/lianjie.svg").default}
                    alt="链接"
                    className="ljIconInPlayer"
                  />
                </div>
              ) : <div className={style.lineproTop}><div>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div></div>}
              <Progress
                className="flex-auto bg-darken-3 rounded"
                innerClassName="rounded-left bg-white"
                value={(currentTime / duration) * 100 || 0}
                {...props}
              />
            </div>

            {/* <Timer
                className={style.slidertime}
                duration={duration}
                currentTime={currentTime} /> */}
            <div className={style.slidertime}>
              {currentTimeWithmh}&nbsp;/&nbsp;{durationWithmh}
            </div>
          </div>
        </div>
        <div className={style.btngroup}>
          <img
            src={require(`./Icon/${isStar ? "star" : "star_on"}.svg`).default}
            alt="svg"
            className={style.iconNormal}
            onClick={toggleStar}
          />
          <img
            src={require("./Icon/share.svg").default}
            alt="svg"
            className={style.iconNormal}
          />
        </div>
        <div className={style.btngroup}>
          {/* <img
            src={require("./Icon/voice.svg").default}
            alt="svg"
            className={style.iconNormal}
          /> */}
          {type == 1 ? (
            <img
              src={require("./Icon/sone.svg").default}
              alt="顺序"
              className={style.iconNormal}
              onClick={setThreeStatus}
            />
          ) : null}
          {type == 2 ? (
            <img
              src={require("./Icon/stwo.svg").default}
              alt="随机"
              className={style.iconNormal}
              onClick={setThreeStatus}
            />
          ) : null}
          {type == 3 ? (
            <img
              src={require("./Icon/sthree.svg").default}
              alt="单曲"
              className={style.iconNormal}
              onClick={setThreeStatus}
            />
          ) : null}
          <div>
            {showPlaylist ? (
              <div className={style.playlistItem}>
                <PlayerListTop toggleShowPlaylist={showPlaylistFun} songsList={songsList} playSongGlobal={playSong} playing={playing} soundCloudAudio={soundCloudAudio}/>
              </div>
            ) : null}
            <div onClick={(e) => showPlaylistFun(e)} className={style.playListicon}>
              <img
                src={require("./Icon/plist.svg").default}
                alt="svg"
                className={style.iconNormal}
              />
              <div className={style.playCount}>{songsList.length}</div>
            </div>
          </div>
        </div>
      </div>
      <style jsx="true">{`
        .ant-slider .ant-slider-track {
          background-color: #c20c0c !important;
        }
        .ant-slider .ant-slider-handle {
          border: 2px solid #c20c0c !important;
        }
        .sb-soundplayer-volume {
          display: flex;
          align-items: center;
          justify-content: center;
        }
        .sb-soundplayer-volume:hover div {
          height: 26px;
        }
        .sb-soundplayer-progress-container {
          background-color: #ddd;
          width: 100%;
          height: 6px;
          overflow: hidden;
          cursor: pointer;
          border-radius: 4px;
        }
        .musicPic {
          cursor: pointer;
        }
        .ljIconInPlayer{
          width: 20px !important;
          height: 20px !important;
          opacity: 0.7;
          margin-left: 7px;
        }
        .ljIconInPlayer:hover{
          opacity: 1;
          cursor: pointer;
        }
        .sb-soundplayer-progress-inner{
          background-color: #C20C0C;
        }
        .sb-soundplayer-volume button{
          color: #C20C0C;
        }
        .sb-soundplayer-volume input[type=range]::-webkit-slider-thumb {
            -webkit-appearance: none;
            height: 12px;
            width: 12px;
            background-color: #C20C0C; 
        }
      `}</style>
    </MinAndMax>
  );
});

const mDispatch = (dispatch) => {
  console.log('dispatch');
  return {
    setNewSongs: (data) => {
      console.log(data, 'data setCurrentSongDetail');
      dispatch(setCurrentSongDetail(data))
    },
    setCurrentTimeAct: (data) => {
      // console.log(data, 'data setCurrentTimeAct');
      dispatch(setCurrentTime(data))
    },
    setCurrentSongDetailAct: (data) => {
      dispatch(setCurrentSongDetail(data))
    }
    // setIsplaying: (data) => {
    //   dispatch(setCurrentSongStatus(data))
    // }
  }
}
const mState = (state) => {
  return {
    onEnd: state.currentDoingInfo.onEnd,
    brotherNodeChangeTime: state.currentDoingInfo.brotherNodeChangeTime
  }
}
export default withSoundCloudAudio(connect(mState, mDispatch)(Player));
